﻿#region Copyright (c) 2013-04, Olaf Kober <amarok.projects@gmail.com>
//================================================================================
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//================================================================================
#endregion

using System;
using System.Collections.Generic;
using System.Threading.Tasks;


namespace Amarok.Agents
{
	/// <summary>
	/// This type implements an in-process message bus that can be used to connect multiple agents. Connected 
	/// agents will receive any message that is published onto the messages bus. Likewise any message published 
	/// by one of the connected agents is automatically published onto the message bus and therefore forwarded 
	/// to all connected agents, including the agent that originally published the message.
	/// </summary>
	public sealed class DefaultMessageBus :
		IMessageBus
	{
		// data
		private readonly DefaultPublisher mPublisher = new DefaultPublisher();


		#region ++ ICompletable Interface ++

		/// <summary>
		/// Gets a Task instance that represents the completion state of the object. This task instance is 
		/// transitioned into the final RunToCompletion state when the object has finally completed.
		/// </summary>
		public Task Completion
		{
			get
			{
				return mPublisher.Completion;
			}
		}


		/// <summary>
		/// Initiates the asynchronous completion of the object. After calling this method the object will complete 
		/// and its <see cref="Completion"/> task will enter a final state after it has processed or discarded all 
		/// previously available messages.
		/// </summary>
		/// 
		/// <param name="discardAvailableMessages">
		/// True to discard all already available messages. False to process all already available messages to 
		/// completion. Defaults to false.</param>
		public void Complete(Boolean discardAvailableMessages = false)
		{
			mPublisher.Complete(discardAvailableMessages);
		}

		#endregion

		#region ++ IDisposable Interface ++

		/// <summary>
		/// When calling <see cref="IDisposable.Dispose"/> all available messages will be discarded and the method 
		/// will block the calling thread until the object has finally completed.
		/// </summary>
		public void Dispose()
		{
			Helper.Dispose(mPublisher);
		}

		#endregion

		#region ++ IAdvertiser Interface ++

		/// <summary>
		/// Subscribes the supplied agent on the publisher. All messages published that match or derive 
		/// from the specified message type and that pass the optional message filter will be forwarded 
		/// to the subscriber.
		/// </summary>
		/// 
		/// <param name="messageType">
		/// The base type of messages for which to subscribe. This type must be assignable to <see cref="Message"/>.</param>
		/// <param name="subscriber">
		/// An agent reference to the agent subscribing for messages.</param>
		/// <param name="messageFilter">
		/// A callback used as content-based filter. Optional, defaults to null.</param>
		/// 
		/// <returns>
		/// An object representing the subscription that can be used to unsubscribe from the publisher, 
		/// or a null value when the advertiser has already be completed.</returns>
		/// 
		/// <exception cref="ArgumentNullException">
		/// A null reference was passed to a method that did not accept it as a valid argument.</exception>
		/// <exception cref="ArgumentException">
		/// A value was passed to a method that did not accept it as a valid argument, because 
		/// the value representing a type is not assignable to the specified target type.</exception>
		public ICompletable Subscribe(Type messageType, AgentReference subscriber, Predicate<Message> messageFilter = null)
		{
			return mPublisher.Subscribe(
				messageType,
				subscriber,
				messageFilter);
		}

		/// <summary>
		/// Subscribes the supplied callback on the publisher. All messages published that match or derive 
		/// from the specified message type and that pass the optional message filter will be forwarded 
		/// to the subscriber.
		/// </summary>
		/// 
		/// <param name="messageType">
		/// The base type of messages for which to subscribe. This type must be assignable to <see cref="Message"/>.</param>
		/// <param name="subscriber">
		/// A callback subscribing for messages.</param>
		/// <param name="messageFilter">
		/// A callback used as content-based filter. Optional, defaults to null.</param>
		/// 
		/// <returns>
		/// An object representing the subscription that can be used to unsubscribe from the publisher, 
		/// or a null value when the advertiser has already be completed.
		/// </returns>
		/// 
		/// <exception cref="ArgumentNullException">
		/// A null reference was passed to a method that did not accept it as a valid argument.</exception>
		/// <exception cref="ArgumentException">
		/// A value was passed to a method that did not accept it as a valid argument, because 
		/// the value representing a type is not assignable to the specified target type.</exception>
		public ICompletable Subscribe(Type messageType, Action<Message> subscriber, Predicate<Message> messageFilter = null)
		{
			return mPublisher.Subscribe(
				messageType,
				subscriber,
				messageFilter);
		}

		#endregion

		#region ++ IPublisher Interface ++

		/// <summary>
		/// Publishes the supplied message and forwards it to interested consumers.
		/// 
		/// The method stores the supplied message in the dispatcher's input message queues of interested consumers and 
		/// returns immediately, meaning it only schedules the message for further processing, but the actual processing 
		/// is done later in other threads.
		/// 
		/// If there is no interested consumer at the time of publishing, then the message will be dropped silently.
		/// 
		/// Messages that are published after completing the publisher will be dropped silently.
		/// </summary>
		/// 
		/// <param name="message">
		/// The message that should be published.</param>
		/// 
		/// <exception cref="ArgumentNullException">
		/// A null reference was passed to a method that did not accept it as a valid argument.</exception>
		public void Publish(Message message)
		{
			mPublisher.Publish(message);
		}

		#endregion

		#region ++ IMessageBus Interface ++

		/// <summary>
		/// Connects the supplied agent with the message bus. Messages published by the agent will be forwarded 
		/// to the message bus. Messages published onto the message bus will be forwarded to the agent.
		/// </summary>
		/// 
		/// <param name="agent">
		/// The agent to connect with the message bus.</param>
		/// 
		/// <returns>
		/// An object representing the subscription that can be used to disconnect the agent from the message bus, 
		/// or a null value when connecting the agent with the message bus was not possible since the message bus 
		/// has already been completed.
		/// </returns>
		/// 
		/// <exception cref="ArgumentNullException">
		/// A null reference was passed to a method that did not accept it as a valid argument.</exception>
		public ICompletable Connect(IAgent agent)
		{
			Verify.NotNull(agent, "agent");

			var connection = new Connection();

			// agent -> message bus
			connection.AgentSubscription = agent.Subscribe(
				typeof(Message),
				_message => mPublisher.Publish(_message)
			);

			// message bus -> agent
			connection.PublisherSubscription = mPublisher.Subscribe(
				typeof(Message),
				agent.ToAgentReference(),
				null
			);

			return connection;
		}

		/// <summary>
		/// Connects the supplied agent with the message bus. Messages published by the agent will be forwarded 
		/// to the message bus. Messages published onto the message bus will be forwarded to the agent, but only
		/// if the message has either no label or the message has a label equal to the label specified as argument.
		/// </summary>
		/// 
		/// <param name="label">
		/// The label used in this connection. Only messages without label or messages with a label that equals this 
		/// argument will be forwarded to the agent.</param>
		/// <param name="agent">
		/// The agent to connect with the message bus.</param>
		/// 
		/// <returns>
		/// An object representing the subscription that can be used to disconnect the agent from the message bus, 
		/// or a null value when connecting the agent with the message bus was not possible since the message bus 
		/// has already been completed.
		/// </returns>
		/// 
		/// <exception cref="ArgumentNullException">
		/// A null reference was passed to a method that did not accept it as a valid argument.</exception>
		public ICompletable Connect(Object label, IAgent agent)
		{
			Verify.NotNull(label, "label");
			Verify.NotNull(agent, "agent");

			var connection = new Connection();

			// agent -> message bus
			connection.AgentSubscription = agent.Subscribe(
				typeof(Message),
				_message => mPublisher.Publish(_message)
			);

			// message bus -> agent
			connection.PublisherSubscription = mPublisher.Subscribe(
				typeof(Message),
				agent.ToAgentReference(),
				_message =>
				{
					if (_message.HasLabel)
						return _message.Label.Equals(label);
					else
						return true;
				}
			);

			return connection;
		}

		#endregion

		#region Nested Types

		private sealed class Connection : CompletableObject
		{
			public ICompletable AgentSubscription;
			public ICompletable PublisherSubscription;


			protected override Task OnComplete(Boolean discardAvailableMessages)
			{
				var tasks = new List<Task>(2);

				if (this.AgentSubscription != null)
				{
					this.AgentSubscription.Complete(discardAvailableMessages);
					tasks.Add(this.AgentSubscription.Completion);
				}

				if (this.PublisherSubscription != null)
				{
					this.PublisherSubscription.Complete(discardAvailableMessages);
					tasks.Add(this.PublisherSubscription.Completion);
				}

				return TaskHelper.WhenAll(tasks);
			}
		}

		#endregion

	}
}
